package edu.gatech.cs4220;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ProfileList extends Activity {
	
	static final String PROFILES_SET = "edu.gatech.cs4220.profiles";
	
	private LocationProfileSet profiles;
	private List<String> profileNames;
	private ListView profileListView;
	private final int CONTEXTMENU_SETITEM = 0;
	private final int CONTEXTMENU_EDITITEM = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profilelist);
		profileNames = new ArrayList<String>();
		profileListView = (ListView)findViewById(R.id.widget36);
		Bundle bun = getIntent().getExtras();
		profiles = (LocationProfileSet)bun.get(PROFILES_SET);
		profileNames.add(profiles.getDefaultProfile().getName());
		for(LocationProfile i : profiles.getProfilesForDisplay())
		{
			profileNames.add(i.getName());
		}
    	// By using setAdpater method in listview we an add string array in list.
    	profileListView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , profileNames));
    	registerForContextMenu(profileListView);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	                                ContextMenuInfo menuInfo) {
	  super.onCreateContextMenu(menu, v, menuInfo);
	  menu.add(0,CONTEXTMENU_SETITEM,0,"Set Profile");
	  menu.add(0,CONTEXTMENU_EDITITEM,0,"Edit Profile");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case CONTEXTMENU_SETITEM:
			//TODO This code should set the profile selected to the current profile
			return true;
		case CONTEXTMENU_EDITITEM:
			//TODO This should lead us to EditProfile with the profile selected
			//profileListView.getAdapter().getItem((int)info.id) is the name of the profile
			Intent myIntent = new Intent(getApplicationContext(), EditProfile.class);
			myIntent.putExtra(ProfileList.PROFILES_SET,profiles);
			myIntent.putExtra(EditProfile.PROFILE_TO_EDIT, profiles.getProfile((String)(profileListView.getAdapter().getItem((int)info.id))));
			startActivityForResult(myIntent, 0);
			return true;
		default:
			return super.onContextItemSelected(item);
	  }
	}
	
	public void backButton(View view)
	{
		finish();
	}
}
